package cn.iocoder.yudao.hires.service.impl;

import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.hires.service.DictCityService;
import cn.iocoder.yudao.hires.vo.DictCityPageReqVO;
import cn.iocoder.yudao.hires.vo.DictCitySaveReqVO;
import cn.iocoder.yudao.hires.vo.DictCityTreeNodeVO;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import cn.iocoder.yudao.hires.entity.DictCityDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.hires.mapper.DictCityMapper;

import javax.annotation.Resource;

import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 行政区划 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class DictCityServiceImpl implements DictCityService {

    @Resource
    private DictCityMapper dictCityMapper;

    @Override
    public String createDictCity(DictCitySaveReqVO createReqVO) {
        // 插入
        DictCityDO dictCity = BeanUtils.toBean(createReqVO, DictCityDO.class);
        dictCityMapper.insert(dictCity);
        // 返回
        return dictCity.getNodeCode();
    }

    @Override
    public void updateDictCity(DictCitySaveReqVO updateReqVO) {
        // 校验存在
        validateDictCityExists(updateReqVO.getNodeCode());
        // 更新
        DictCityDO updateObj = BeanUtils.toBean(updateReqVO, DictCityDO.class);
        dictCityMapper.updateById(updateObj);
    }

    @Override
    public void deleteDictCity(String id) {
        // 校验存在
        validateDictCityExists(id);
        // 删除
        dictCityMapper.deleteById(id);
    }

    private void validateDictCityExists(String id) {
        if (dictCityMapper.selectById(id) == null) {
            throw exception(new ErrorCode(500, "行政区划不存在"));
        }
    }

    @Override
    public DictCityDO getDictCity(String id) {
        return dictCityMapper.selectById(id);
    }

    @Override
    public PageResult<DictCityDO> getDictCityPage(DictCityPageReqVO pageReqVO) {
        return dictCityMapper.selectPage(pageReqVO);
    }


    @Override
    public List<DictCityDO> getList() {
        return dictCityMapper.selectList();
    }

    @Override
    /**
     * 构建行业类别树形结构
     *
     * @param categories 所有行业类别列表
     * @return 树形结构
     */ public List<DictCityTreeNodeVO> buildCategoryTree(List<DictCityDO> categories) {
        if (CollectionUtils.isEmpty(categories)) {
            return Collections.emptyList();
        }

        // 转换为 Map 结构，key 是 categoryId
        Map<String, DictCityTreeNodeVO> nodeMap = categories.stream().map(category -> {
            DictCityTreeNodeVO node = new DictCityTreeNodeVO();
            node.setNodeCode(category.getNodeCode());
            node.setNodeName(category.getNodeName());
            node.setCodeParent(category.getCodeParent());
            node.setNodeLevel(category.getNodeLevel());
            return node;
        }).collect(Collectors.toMap(DictCityTreeNodeVO::getNodeCode, node -> node));

        // 构建树形结构
        List<DictCityTreeNodeVO> tree = new ArrayList<>();
        for (DictCityTreeNodeVO node : nodeMap.values()) {
            if ("0".equals(node.getCodeParent())) {
                // 一级节点
                tree.add(node);
            } else {
                // 子节点，添加到父节点的 children 中
                DictCityTreeNodeVO parentNode = nodeMap.get(node.getCodeParent());
                if (parentNode != null) {
                    if (parentNode.getChildren() == null) {
                        parentNode.setChildren(new ArrayList<>());
                    }
                    parentNode.getChildren().add(node);
                }
            }
        }

        // 对每个层级的节点按 orderNum 排序
        sortTreeNodes(tree);
        return tree;
    }


    /**
     * 递归排序树节点
     *
     * @param nodes 节点列表
     */
    private void sortTreeNodes(List<DictCityTreeNodeVO> nodes) {
        if (CollectionUtils.isEmpty(nodes)) {
            return;
        }

        // 按 orderNum 排序当前层级
        nodes.sort(Comparator.comparingInt(DictCityTreeNodeVO::getNodeLevel));

        // 递归排序子节点
        for (DictCityTreeNodeVO node : nodes) {
            if (node.getChildren() != null) {
                sortTreeNodes(node.getChildren());
            }
        }
    }

}